package filereaders;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


/**
 * This class will, given a file, attempt to
 * create a parser to parse it.
 * 
 * @author Paul Dannenberg
 * 
 */

public class ParserFactory {

    private List<Parser> myParsers;

    /**
     * Creates an object that can determine
     * the choice of parser for a particular
     * datafile.
     */
    public ParserFactory() {
        myParsers = new ArrayList<Parser>();
    }

    /*
     * Add any new file types that can now be
     * parsed in this method.
     */
    private void fillFileExtensionOptions(File file) {

        myParsers.add(new TxtColumnParser(file));
        myParsers.add(new TxtRowParser(file));
        myParsers.add(new XmlParser(file));
    }

    /**
     * Selects the correct parser for the user of based
     * on the file he or she wishes to read.
     * 
     * @param file The file to be parsed.
     * @return A parser capable of reading the file, or
     *         null if the factory has no parser capable of doing
     *         this.
     */
    public Parser createParser(File file) {
        fillFileExtensionOptions(file);
        return findCorrectParser();
    }

    private Parser findCorrectParser() {
        for (Parser p : myParsers) {
            if (p.canParseFile()) {
                return p;
            }
        }
        return null;
    }
}
